package theme

import (
	"html/template"
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Core"
	"strings"
	"bytes"
)

type Theme struct {

}

func (this Theme) Setup() {
	Core.SetFunc("ThemeDefault", this.setDefaultTheme)
	Core.SetFunc("ThemeImport", this.setTheme)
	Core.SetTemplateFunc("CssFile", func(cssFiles map[string]string) template.HTML {
			html := ""
			for _, v := range cssFiles {
				html += `<link rel="stylesheet" href="/` + v + `" type="text/css"/>`
			}
			return template.HTML(html)
		})
	Core.SetTemplateFunc("JsFile", func(jsFiles map[string]string) template.HTML {
			html := ""
			for _, v := range jsFiles {
				html += `<script type="text/javascript" src="/` + v + `"></script>`
			}
			return template.HTML(html)
		})
	Core.SetTemplateFunc("Text", HTML)
	Core.SetTemplateFunc("TextHTML", HtmlText)
}

func (_ Theme) setDefaultTheme(b *Core.HxBehavior) string {
	t := b.Template()
	t.With("user", "header.html")
	t.With("user", "footer.html")
	t.Css("style.css")
	t.Js("js/home.js")
	t.Share("THEME",Core.Config.String("theme.user"))
	return ""
}

func (_ Theme) setTheme(b *Core.HxBehavior, theme string, file string) string {
	t := b.Template()
	t.With(theme, file)
	return ""
}

// strip html tags
// from https://github.com/kennygrant/sanitize/
func HTML(s string) (output string) {

	output = ""

	// Shortcut strings with no tags in them
	if !strings.ContainsAny(s, "<>") {
		output = s
	} else {

		// First remove line breaks etc as these have no meaning outside html tags (except pre)
		// this means pre sections will lose formatting... but will result in less uninentional paras.
		s = strings.Replace(s, "\n", "", -1)

		// Then replace line breaks with newlines, to preserve that formatting
		s = strings.Replace(s, "</p>", "\n", -1)
		s = strings.Replace(s, "<br>", "\n", -1)
		s = strings.Replace(s, "</br>", "\n", -1)

		// Walk through the string removing all tags
		b := bytes.NewBufferString("")
		inTag := false
		for _, r := range s {
			switch r {
			case '<':
				inTag = true
			case '>':
				inTag = false
			default:
				if !inTag {
					b.WriteRune(r)
				}
			}
		}
		output = b.String()
	}

	// In case we have missed any tags above, escape the text - removes <, >, &, ' and ".
	output = template.HTMLEscapeString(output)

	// Remove a few common harmless entities, to arrive at something more like plain text
	// This relies on having removed *all* tags above
	output = strings.Replace(output, "&nbsp;", " ", -1)
	output = strings.Replace(output, "&quot;", "\"", -1)
	output = strings.Replace(output, "&apos;", "'", -1)
	output = strings.Replace(output, "&#34;", "\"", -1)
	output = strings.Replace(output, "&#39;", "'", -1)
	// NB spaces here are significant - we only allow & not part of entity
	output = strings.Replace(output, "&amp; ", "& ", -1)
	output = strings.Replace(output, "&amp;amp; ", "& ", -1)

	return output
}


func HtmlText(str template.HTML) string {
	return HTML(string(str))
}
